<template>
  <up-popup :show="show" @close="handleClose" mode="center" :round="20" :closeable="true" :customStyle="{
    width: '600rpx',
    maxHeight: '80vh',
    overflow: 'hidden',
  }">
    <view class="create-task-modal">
      <view class="modal-header">
        <text class="modal-title">创建场内车辆核验任务</text>
      </view>

      <view class="modal-content">
        <view class="form-item">
          <text class="form-label">任务名称</text>
          <up-input v-model="formData.taskName" placeholder="请输入任务名称" :customStyle="{
            backgroundColor: '#f8f9fa',
            borderRadius: '12rpx',
            padding: '20rpx',
          }" />
        </view>

        <view class="form-item">
          <text class="form-label">核验范围</text>
          <up-radio-group v-model="formData.verifyScope" @change="handleScopeChange">
            <up-radio name="all" label="全部场内车辆" :customStyle="{
              marginBottom: '20rpx',
            }" />
            <up-radio name="area" label="指定区域车辆" :customStyle="{ marginBottom: '20rpx' }" />
            <up-radio name="custom" label="自定义车辆列表" :customStyle="{ marginBottom: '20rpx' }" />
          </up-radio-group>
        </view>

        <view class="form-item" v-if="formData.verifyScope === 'area'">
          <text class="form-label">选择区域</text>
          <up-picker :show="areaPickerShow" :columns="areaColumns" @confirm="handleAreaConfirm"
            @cancel="areaPickerShow = false" />
          <up-input v-model="formData.selectedAreaText" placeholder="请选择核验区域" readonly @click="areaPickerShow = true"
            :customStyle="{
              backgroundColor: '#f8f9fa',
              borderRadius: '12rpx',
              padding: '20rpx',
            }" />
        </view>

        <view class="form-item" v-if="formData.verifyScope === 'custom'">
          <text class="form-label">车辆列表</text>
          <up-textarea v-model="formData.vehicleList" placeholder="请输入车牌号，多个车牌号用换行分隔" :maxlength="1000" :customStyle="{
            backgroundColor: '#f8f9fa',
            borderRadius: '12rpx',
            padding: '20rpx',
            minHeight: '200rpx',
          }" />
        </view>

        <view class="form-item">
          <text class="form-label">执行人</text>
          <up-picker :show="executorPickerShow" :columns="executorColumns" @confirm="handleExecutorConfirm"
            @cancel="executorPickerShow = false" />
          <up-input v-model="formData.executorText" placeholder="请选择执行人" readonly @click="executorPickerShow = true"
            :customStyle="{
              backgroundColor: '#f8f9fa',
              borderRadius: '12rpx',
              padding: '20rpx',
            }" />
        </view>

        <view class="form-item">
          <text class="form-label">计划开始时间</text>
          <up-datetime-picker :show="datePickerShow" v-model="formData.startTime" mode="datetime"
            @confirm="handleDateConfirm" @cancel="datePickerShow = false" />
          <up-input v-model="formData.startTimeText" placeholder="请选择计划开始时间" readonly @click="datePickerShow = true"
            :customStyle="{
              backgroundColor: '#f8f9fa',
              borderRadius: '12rpx',
              padding: '20rpx',
            }" />
        </view>

        <view class="form-item">
          <text class="form-label">任务描述</text>
          <up-textarea v-model="formData.description" placeholder="请输入任务描述（可选）" :maxlength="500" :customStyle="{
            backgroundColor: '#f8f9fa',
            borderRadius: '12rpx',
            padding: '20rpx',
            minHeight: '120rpx',
          }" />
        </view>
      </view>

      <view class="modal-footer">
        <up-button text="取消" @click="handleClose" :customStyle="{
          flex: 1,
          marginRight: '20rpx',
          height: '80rpx',
          backgroundColor: '#f5f5f5',
          color: '#666666',
          border: 'none',
        }" />
        <up-button text="确认创建" type="primary" @click="handleConfirm" :loading="loading" :customStyle="{
          flex: 1,
          height: '80rpx',
        }" />
      </view>
    </view>
  </up-popup>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";

// Props
interface Props {
  show: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  show: false,
});

// Emits
const emit = defineEmits<{
  "update:show": [value: boolean];
  confirm: [data: any];
}>();

// 响应式数据
const loading = ref(false);
const areaPickerShow = ref(false);
const executorPickerShow = ref(false);
const datePickerShow = ref(false);

// 表单数据
const formData = reactive({
  taskName: "",
  verifyScope: "all",
  selectedArea: "",
  selectedAreaText: "",
  vehicleList: "",
  executor: "",
  executorText: "",
  startTime: "",
  startTimeText: "",
  description: "",
});

// 区域选择器数据
const areaColumns = ref([
  [
    { text: "A区", value: "area_a" },
    { text: "B区", value: "area_b" },
    { text: "C区", value: "area_c" },
    { text: "D区", value: "area_d" },
  ],
]);

// 执行人选择器数据
const executorColumns = ref([
  [
    { text: "张三", value: "zhangsan" },
    { text: "李四", value: "lisi" },
    { text: "王五", value: "wangwu" },
    { text: "赵六", value: "zhaoliu" },
  ],
]);

// 监听显示状态
watch(
  () => props.show,
  (newVal) => {
    if (newVal) {
      resetForm();
    }
  }
);

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    taskName: "",
    verifyScope: "all",
    selectedArea: "",
    selectedAreaText: "",
    vehicleList: "",
    executor: "",
    executorText: "",
    startTime: "",
    startTimeText: "",
    description: "",
  });
};

// 关闭弹窗
const handleClose = () => {
  emit("update:show", false);
};

// 核验范围变化
const handleScopeChange = (value: string) => {
  formData.verifyScope = value;
  if (value !== "area") {
    formData.selectedArea = "";
    formData.selectedAreaText = "";
  }
  if (value !== "custom") {
    formData.vehicleList = "";
  }
};

// 区域选择确认
const handleAreaConfirm = (value: any) => {
  formData.selectedArea = value.value[0];
  formData.selectedAreaText = value.value[0]
    ? areaColumns.value[0].find((item) => item.value === value.value[0])
      ?.text || ""
    : "";
  areaPickerShow.value = false;
};

// 执行人选择确认
const handleExecutorConfirm = (value: any) => {
  formData.executor = value.value[0];
  formData.executorText = value.value[0]
    ? executorColumns.value[0].find((item) => item.value === value.value[0])
      ?.text || ""
    : "";
  executorPickerShow.value = false;
};

// 日期选择确认
const handleDateConfirm = (value: any) => {
  formData.startTime = value.value;
  formData.startTimeText = value.value;
  datePickerShow.value = false;
};

// 确认创建
const handleConfirm = async () => {
  // 表单验证
  if (!formData.taskName.trim()) {
    uni.showToast({
      title: "请输入任务名称",
      icon: "none",
    });
    return;
  }

  if (!formData.executor) {
    uni.showToast({
      title: "请选择执行人",
      icon: "none",
    });
    return;
  }

  if (!formData.startTime) {
    uni.showToast({
      title: "请选择计划开始时间",
      icon: "none",
    });
    return;
  }

  if (formData.verifyScope === "area" && !formData.selectedArea) {
    uni.showToast({
      title: "请选择核验区域",
      icon: "none",
    });
    return;
  }

  if (formData.verifyScope === "custom" && !formData.vehicleList.trim()) {
    uni.showToast({
      title: "请输入车辆列表",
      icon: "none",
    });
    return;
  }

  loading.value = true;

  try {
    // 处理车辆列表
    let vehicleArray = [];
    if (formData.verifyScope === "custom") {
      vehicleArray = formData.vehicleList
        .split("\n")
        .map((plate) => plate.trim())
        .filter((plate) => plate.length > 0);
    }

    const taskData = {
      taskName: formData.taskName,
      verifyScope: formData.verifyScope,
      selectedArea: formData.selectedArea,
      vehicleList: vehicleArray,
      executor: formData.executor,
      startTime: formData.startTime,
      description: formData.description,
    };

    emit("confirm", taskData);
    emit("update:show", false);
  } catch (error) {
    console.error("创建任务失败:", error);
  } finally {
    loading.value = false;
  }
};
</script>

<style lang="scss" scoped>
.create-task-modal {
  background-color: #ffffff;
  border-radius: 20rpx;
  overflow: hidden;
}

.modal-header {
  padding: 40rpx 30rpx 30rpx;
  text-align: center;
  border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333333;
}

.modal-content {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.form-item {
  margin-bottom: 30rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 16rpx;
  font-weight: 500;
}

.modal-footer {
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
  display: flex;
  gap: 20rpx;
}
</style>
